package com.open.custom.api.service.business.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import com.open.custom.api.config.properties.LocalFsProperties;
import com.open.custom.api.service.business.OssClient;
import com.open.custom.api.utils.OssIdUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
public class LocalFsOssClientAdapter implements OssClient {

    LocalFsProperties localFsProperties;

    public LocalFsOssClientAdapter(LocalFsProperties localFsProperties) {
        this.localFsProperties = localFsProperties;
    }

    @Override
    public boolean exist(String fileId) {
        String path = getFilePath(fileId);
        return Files.exists(Path.of(path));
    }

    @Override
    public String save(byte[] bytes) {
        return save(null, bytes);
    }

    @Override
    public String save(String fileId, byte[] bytes) {
        if (ObjUtil.isEmpty(fileId)) {
            fileId = OssIdUtil.genUUID();
        }
        makePaths(fileId);
        FileUtil.writeBytes(bytes, getFilePath(fileId));
        return fileId;
    }

    @Override
    public byte[] get(String fileId) {
        String path = getFilePath(fileId);
        try (final FileInputStream fileInputStream = new FileInputStream(path);) {
            return fileInputStream.readAllBytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean delete(String fileId) {
        String path = getFilePath(fileId);
        try {
            return Files.deleteIfExists(Path.of(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String makePaths(String id) {
        final String fileDirPath = getFileDirPath(id);
        File f = new File(fileDirPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        return fileDirPath;
    }

    private String getFilePath(String id) {
        return getFileDirPath(id) + "/" + id;
    }

    private String getFileDirPath(String id) {
//        return localFsProperties.getRootPath() + "/"
//                + id.substring(id.length() - 6, id.length() - 3)
//                + "/" + id.substring(id.length() - 3);
        // yyyyMMddHHmmssSSS
        return localFsProperties.getRootPath() + "/" + id.substring(0, 6) + "/" + id.substring(6, 8);
    }

}
